package com.yuneec.droneservice.command;

import com.yuneec.droneservice.model.CameraInfo;
import com.yuneec.droneservice.request.IResponse;
import com.yuneec.droneservice.utils.ByteUtils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * Created by gjw on 2017/3/27.
 */

public class GetCameraInfo extends BaseCommand {

    public GetCameraInfo() {
        super(MAV_RC_COMMAND.MAV_RC_CMD_GET_CAMERA_INFO);
    }

    @Override
    public IResponse toResponse(byte[] data, int off, int len) {
        int code = data[off + 1] & 0xff;
        IResponse<CameraInfo> response = new IResponse(ids(), code);
        if (code == MAV_RC_ERROR_CODE.MAV_RC_ERR_SUCCESS) {
            CameraInfo cameraInfo = new CameraInfo();
            try {
                int index = 2;
                int ssidLen = ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + 2, off + index + 2), IS_BIGENDIAN);
                if (ssidLen > 0) {
                    try {
                        cameraInfo.setSsid(new String(Arrays.copyOfRange(data, off + index + 2, off + index + 2 + ssidLen), "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                index = index + 2 + ssidLen;
                int ipLen = ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + index, off + index + 2), IS_BIGENDIAN);
                if (ipLen > 0) {
                    try {
                        cameraInfo.setIp(new String(Arrays.copyOfRange(data, off + index + 2, off + index + 2 + ipLen), "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                index = index + 2 + ipLen;
                cameraInfo.setFrequency(ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + index, off + index + 2), IS_BIGENDIAN));
                cameraInfo.setLevel(ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + index + 2, off + index + 4), IS_BIGENDIAN));
            } catch (Exception e) {
                e.printStackTrace();
            }
            response.setParam(cameraInfo);
        }
        return response;
    }

}
